import Vue from "vue";
import App from "./App.vue";
import ElementUI from "element-ui";
import { Message } from "element-ui";
import "./assets/style/elementui.less";
import "./assets/fonts/iconfont/iconfont.css";
import "./assets/style/common.less";
import "./assets/fonts/iconfont/iconfont.json";
import "element-ui/lib/theme-chalk/index.css";
import router from "./router/index";
import store from "./store/index";
import axios from "axios";
import qs from "qs";
import * as echarts from "echarts";
import * as Highcharts from "highcharts";
import Highcharts3D from "highcharts/highcharts-3d";
import "echarts-gl";
import LsdTable from "@/components/LsdTable"; // 表格组件
import LsdForm from "@/components/LsdForm"; // 表单组件
import filterTitle from "@/components/filterTitle"; // 列表页筛选组件
import LsdDialog from "@/components/LsdDialog"; // 弹窗组件
import LsdDialogTitle from "@/components/LsdDialogTitle"; // 弹窗折叠器组件
import DialogForm from "@/components/dialogForm"; // 弹窗表单组件
import DialogForm2 from "@/components/dialogForm2"; // 弹窗表单组件
import DialogChoose from "@/components/DialogChoose"; // 弹窗选择组件
import HpSelect from "@/components/HpSelect"; // 弹窗选择组件
import WorkFlow from "@/components/WorkFlow"; // 工作流下一步操作人组件
import microApp from "@micro-zoe/micro-app"; // 微应用
import common from "./utils/common";
import start from "./micros/index";
import "@/directive/index"; // table 滚动加载
import iscConfig from "./config/iscConfig";
import { getMenuTreeByRole } from "@/api/SystemConfig/menuConfig.js";
microApp.start({});
start();

axios.defaults.baseURL = "http://";
Vue.prototype.common = common;
// Vue.prototype.$stringToNumber = stringToNumber;
Vue.prototype.$http = axios;
Vue.prototype.$eventBus = new Vue();
Vue.prototype.$echarts = echarts;
Vue.prototype.$Highcharts = Highcharts;
Vue.prototype.$qs = qs;
Highcharts3D(Highcharts);
Vue.component("LsdTable", LsdTable);
Vue.component("LsdForm", LsdForm);
Vue.component("filterTitle", filterTitle);
Vue.component("LsdDialog", LsdDialog);
Vue.component("LsdDialogTitle", LsdDialogTitle);
Vue.component("DialogForm", DialogForm);
Vue.component("DialogForm2", DialogForm2);
Vue.component("DialogChoose", DialogChoose);
Vue.component("HpSelect", HpSelect);
Vue.component("WorkFlow", WorkFlow);


Vue.use(ElementUI);

Vue.config.productionTip = false;
Vue.prototype.$store = store;
const whiteList = [
  "/NoIscLogin", "/Login"
];
router.beforeEach((to, from, next) => {
  const org = JSON.parse(sessionStorage.getItem("org")) || false;
  const role = JSON.parse(sessionStorage.getItem("role")) || false;
  const account = JSON.parse(sessionStorage.getItem("account")) || false;
  if (org && role && account) {
    if (to.path === "/Login") {
      next("/");
    } else {
      // 判断菜单信息是否已经获取
      if (store.state.menuTree.length === 0) {
        getMenuTreeByRole(role.roleId).then(menuConfig => {
          if (menuConfig.length > 0) {
            // 去掉系统配置菜单下的子模块内容
            let result = menuConfig.map(i => {
              if (i.menuName === "系统配置") {
                i.children = [];
              }
              return i;
            });
            result = result.filter(item => item.menuName !== "APP端");
            store.commit("SET_MenuTree", result);
            next();
          } else {
            Message.error("当前角色无菜单权限，请先配置菜单");
            sessionStorage.clear();
            next("/Login");
          }
        });
      } else {
        const menuList = Object.assign([], store.state.menuTree);
        const MenuIndex = Number(sessionStorage.getItem("MenuIndex"));
        /**
         * 递归判断当前角色是否有当前跳转路由的菜单权限、判断是否有某个模块的菜单权限
         * @param list 当前角色菜单集合
         * @param type 1.path,判断当前角色是否有当前路由的菜单权限。2.detail,判断是否有某个模块的菜单权限
         * @param name 当type为detail时，代表判断是否有哪个模块权限的菜单名称
         */
        const isHasPath = (list, type, name) => {
          return list.some(item => {
            if (type === "path") {
              if (item.menuUrl.split("?")[0] === to.path) {
                const targetId = item.parent && item.parent !== "1480016250535968" ? item.parent : item.id;
                // 判断当前跳转的菜单索引并设置高亮
                if (targetId != MenuIndex) {
                  store.commit("SET_MenuIndex", targetId);
                }
                return true;
              } else if (item.children) {
                return isHasPath(item.children, "path");
              } else {
                return false;
              }
            } else if (type === "detail") {
              if (item.menuName === name) {
                return true;
              } else if (item.children) {
                return isHasPath(item.children, "detail", name);
              } else {
                return false;
              }
            }
          });
        };
        // 判断是否有某个模块菜单权限，如果有就往白名单中加入该模块需要跳转的详情路由
        const checkDetailsList = [
          {
            name: "到岗到位",
            detailPath: ["NoticeDetail"]
          },
          {
            name: "预警信息",
            detailPath: ["InformationDetail", "NoticeDetail"]
          },
          {
            name: "预警研判",
            detailPath: ["EarlyJudgmentDetail", "NoticeDetail"]
          },
          {
            name: "预警通知单",
            detailPath: ["NoticeDetail", "notificationFeedbackDetail"]
          },
          {
            name: "预警日报",
            detailPath: ["WarningDailyDetail"]
          },
          {
            name: "预警任务", // 对应模块名字
            detailPath: ["WarningActionDetail"]// 对应详情模块路由地址
          },
          {
            name: "调整及解除",
            detailPath: ["NoticeDetail"]
          },
          {
            name: "应急事件",
            detailPath: ["EmergencyDetail", "EmergencyResponseinfo"]
          },
          {
            name: "灾情信息",
            detailPath: ["EmergencyDetail"]
          },
          {
            name: "响应命令",
            detailPath: ["EmergencyResponseFeedbackDetail"]
          },
          {
            name: "响应研判",
            detailPath: ["EmergencyResponseinfo", "YpDetail", "EmergencyDetail"]
          },
          {
            name: "客户服务",
            detailPath: ["Failurerepairinfo"]
          },
          {
            name: "应急指挥部",
            detailPath: ["EmergencyResponseinfo", "headquarters"]
          },
          {
            name: "灾情勘察",
            detailPath: ["StatisticalDetails", "TransmissionDetails", "PowerTransformationDetails", "PowerDistributionDetails", "MarketingDetails", "EmergencyResponseinfo"]
          },
          {
            name: "应急会商",
            detailPath: ["web/conference/list1"]
          },
          {
            name: "资源调配",
            detailPath: ["ResourceRequestDetail", "ResourceDispatchDetail", "EmergencyResponseinfo", "RepairPersonnel", "CadrePersonnel", "RepairVehicles", "TransportVehicles", "SpecialVehicles", "EquipStatistic", "SuppliesStatistic"]
          },
          {
            name: "应急日报",
            detailPath: ["EmergencyDailyReportDetail", "EmergencyResponseinfo"]
          },
          {
            name: "调整与终止",
            detailPath: ["EmergencyResponseinfo"]
          },
          {
            name: "知识库",
            detailPath: ["KnowledgeBaseDetail", "KnowledgeBasePreview"]
          },
          {
            name: "预案管理",
            detailPath: ["PlanManagementDetail", "PlanManagementPreview"]
          },
          {
            name: "值班管理",
            detailPath: ["DutyStatisticsDetail", "NoticeDetail", "EmergencyResponseinfo"]
          },
          {
            name: "抢修任务",
            detailPath: ["RepairTask"]
          }
        ];
        // 设置系统配置模块、消息代办、whiteList、对应模块详情白名单
        const detailPassList = ["SystemConfig", "MessageAgentList"];
        checkDetailsList.forEach(({ name, detailPath }) => {
          if (detailPath) {
            detailPath.forEach(item => {
              if (item && to.path.includes(item) && isHasPath(menuList, "detail", name)) {
                detailPassList.push(...detailPath);
              }
            });
          }
        });
        const passList = [...new Set([...detailPassList, ...whiteList])];
        const isPassPath = passList.some(i => to.path.includes(i)) || to.path === "/index";
        if (isHasPath(menuList, "path") || isPassPath) {
          next();
        } else {
          Message.error("当前角色无此模块权限!");
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      // 白名单，直接进入
      next();
    } else {
      if (iscConfig.nodeEnv === "production") {
        // 生产环境走ISC
        iscConfig.judgeISC();
      } else {
        next("/Login");
      }
    }
  }
});

new Vue({
  router,
  store,
  render: (h) => h(App)
}).$mount("#app");
